import 'package:flutter/material.dart';
import 'package:inmotion_pro/l10n/local.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';

import '../../../config/const.dart';
import '../../../config/r.dart';
import '../controller.dart';

// 邮箱注册表单
class EmailRegisterForm extends StatefulWidget {
  final Function(AuthMode) onSwitchAuthMode;

  // 发送验证码，把手机号传出去，同时外面传进来一个bool值表示是否发送成功
  final Function(String, Function(bool)) sendVerificationCodeAction;

  // 使用邮箱注册
  final Function(String, String, String) registerWithEmailAction;

  // 修改邮箱与邮箱注册类似，所以直接复用邮箱注册的逻辑
  final bool isRegisterMode;

  const EmailRegisterForm({
    super.key,
    required this.onSwitchAuthMode,
    required this.sendVerificationCodeAction,
    required this.registerWithEmailAction,
    this.isRegisterMode = true,
  });

  @override
  State<EmailRegisterForm> createState() => _RegisterFormState();
}

class _RegisterFormState extends State<EmailRegisterForm> {
  final _formKey = GlobalKey<FormState>();
  final _emailController = TextEditingController();
  final _passwordController = TextEditingController();
  final _confirmPasswordController = TextEditingController();
  final _verificationCodeController = TextEditingController();
  bool _countdownActive = false;
  int _countdownSeconds = 60;
  bool _obscurePassword = true;
  bool _obscureConfirmPassword = true;
  bool _isSendAction = false;

  void _startCountdown() {
    if (_countdownActive) return;

    _isSendAction = true;

    if (!_formKey.currentState!.validate()) {
      return;
    }

    widget.sendVerificationCodeAction(
      _emailController.text.trim(),
      (success) {
        if (success) {
          setState(() {
            _countdownActive = true;
            _countdownSeconds = 60;
          });

          // Start countdown timer
          Future.delayed(const Duration(seconds: 1), () {
            if (mounted) _updateCountdown();
          });
        }
      },
    );
  }

  void _updateCountdown() {
    // 关键修复：检查组件是否仍然挂载
    if (!mounted) return;

    setState(() {
      _countdownSeconds--;
    });

    if (_countdownSeconds > 0) {
      Future.delayed(const Duration(seconds: 1), _updateCountdown);
    } else {
      setState(() {
        _countdownActive = false;
      });
    }
  }

  void _submit() async {
    _isSendAction = false;
    if (!_formKey.currentState!.validate()) {
      return;
    }

    widget.registerWithEmailAction(
      _emailController.text.trim(),
      _passwordController.text.trim(),
      _verificationCodeController.text.trim(),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (widget.isRegisterMode) ...[
            Text(
              local.register_new_account_using_email,
              style: const TextStyle(
                color: Colors.grey,
              ),
            ),
            const SizedBox(height: 24),
          ],

          // Email Field
          TextFormField(
            controller: _emailController,
            keyboardType: TextInputType.emailAddress,
            maxLength: emailMaxLength,
            decoration: InputDecoration(
              labelStyle: TextStyle(
                  color: const Color(0xFFEEEEEE).withOpacity(0.6),
                  fontSize: 14),
              labelText: local.email_address,
              prefixIcon: Image.asset(R.emailIcon, width: 18, height: 18),
              counterText: '',
            ),
            validator: (value) {
              if (value == null || value.isEmpty) {
                return local.please_enter_your_email_address;
              }
              if (!value.contains('@')) {
                return local.please_enter_valid_email_address;
              }
              return null;
            },
          ),
          const SizedBox(height: 16),

          TextFormField(
            controller: _verificationCodeController,
            keyboardType: TextInputType.number,
            maxLength: verificationCodeLength,
            decoration: InputDecoration(
              labelStyle: TextStyle(
                  color: const Color(0xFFEEEEEE).withOpacity(0.6),
                  fontSize: 14),
              labelText: local.verification_code,
              prefixIcon: Image.asset(R.codeIcon, width: 18, height: 18),
              suffixIcon: TextButton(
                onPressed: _countdownActive ? null : _startCountdown,
                child: Text(
                  _countdownActive ? '$_countdownSeconds s' : local.send,
                  style: TextStyle(
                    color: _countdownActive ? Colors.grey : LxCol.theme,
                  ),
                ),
              ),
              counterText: '',
            ),
            validator: (value) {
              if (_isSendAction) return null;
              if (value == null || value.isEmpty || value.length != 6) {
                return local.please_enter_valid_code(verificationCodeLength);
              }
              return null;
            },
          ),

          const SizedBox(height: 16),
          if (widget.isRegisterMode) ...[
            // Password Field
            TextFormField(
              controller: _passwordController,
              obscureText: _obscurePassword,
              maxLength: passwordMaxLength,
              decoration: InputDecoration(
                labelStyle: TextStyle(
                    color: const Color(0xFFEEEEEE).withOpacity(0.6),
                    fontSize: 14),
                labelText: local.password,
                prefixIcon: Image.asset(R.loginPwdIcon, width: 18, height: 18),
                suffixIcon: IconButton(
                  icon: Icon(_obscurePassword
                      ? Icons.visibility
                      : Icons.visibility_off),
                  onPressed: () {
                    setState(() {
                      _obscurePassword = !_obscurePassword;
                    });
                  },
                ),
                counterText: '',
              ),
              validator: (value) {
                if (_isSendAction) return null;
                if (value == null || value.isEmpty) {
                  return local.please_enter_your_password;
                }
                if (value.length < passwordMinLength) {
                  return local.enter_password_by_register(
                      passwordMinLength, passwordMaxLength);
                }
                return null;
              },
            ),
            const SizedBox(height: 16),

            // Confirm Password Field
            TextFormField(
              controller: _confirmPasswordController,
              obscureText: _obscureConfirmPassword,
              maxLength: passwordMaxLength,
              decoration: InputDecoration(
                labelStyle: TextStyle(
                    color: const Color(0xFFEEEEEE).withOpacity(0.6),
                    fontSize: 14),
                labelText: local.confirm_password,
                prefixIcon: Image.asset(R.loginPwdIcon, width: 18, height: 18),
                suffixIcon: IconButton(
                  icon: Icon(_obscureConfirmPassword
                      ? Icons.visibility
                      : Icons.visibility_off),
                  onPressed: () {
                    setState(() {
                      _obscureConfirmPassword = !_obscureConfirmPassword;
                    });
                  },
                ),
                counterText: '',
              ),
              validator: (value) {
                if (_isSendAction) return null;
                if (value == null || value.isEmpty) {
                  return local.please_confirm_password;
                }
                if (value != _passwordController.text) {
                  return local.passwords_do_not_match;
                }
                return null;
              },
            ),
          ],
          SizedBox(height: widget.isRegisterMode ? 24 : 100),

          // Register Button
          SizedBox(
            width: double.infinity,
            child: ElevatedButton(
              onPressed: _submit,
              style: ElevatedButton.styleFrom(
                backgroundColor: LxCol.theme.withOpacity(0.8),
                padding: const EdgeInsets.symmetric(vertical: 16),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                ),
              ),
              child: Text(
                  widget.isRegisterMode ? local.register : local.confirm,
                  style: const TextStyle(fontSize: 16, color: Colors.white)),
            ),
          ),
          const SizedBox(height: 24),
          if (widget.isRegisterMode) ...[
            SizedBox(
              width: double.infinity,
              child: Wrap(
                spacing: 2.0, // 水平间距
                runSpacing: 0.0, // 垂直间距
                crossAxisAlignment: WrapCrossAlignment.center,
                alignment: WrapAlignment.center,
                children: [
                  Text(
                    local.already_have_account,
                    style: TextStyle(
                        color: Colors.white.withOpacity(0.6), fontSize: 12),
                  ),
                  TextButton(
                    onPressed: () {
                      widget.onSwitchAuthMode(AuthMode.emailLogin);
                    },
                    child: Text(
                      local.login_now,
                      style: TextStyle(
                          color: Colors.white.withOpacity(0.6), fontSize: 12),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ],
      ),
    );
  }
}
